<template>
	<!-- 从XX导入好友 -->
	<view class="gather-import-box">
		<NavBar
			:title="title"
			:leftText="'取消'"
			:rightText="rightText"
			@click-left="onClickLeft"
			@click-right="onClickRight"
		/>

		<view class="age-search" v-if="importType === 'age'">
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input type="number" v-model="ageQuery.min" placeholder="输入最小年龄段" />
				<text>至</text>
				<input type="number" v-model="ageQuery.max" placeholder="输入最大年龄段" />
			</view>
			<text class="btn" @click="ageSearch">搜索</text>
		</view>
		<view v-else class="cu-bar search">
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input type="text" v-model="keywords" placeholder="输入搜索的关键词" confirm-type="search" @input="search" />
			</view>
		</view>
		<checkbox-group>
			<view class="list">
				<view class="item" v-for="(item, index) in list" :key="index" @click.stop="checkboxChange(item)">
					<view :class="['checkbox']">
						<view :class="`checkmark-${item.checked}`"></view>
					</view>
					<view class="item-right">
						<view class="item-title">
							<view class="item-title__text text-one">
								{{ item.title || item.name }}
							</view>
							<view class="item-num" v-if="importType === 'age'"> （{{ item.friend[0].age }}岁） </view>
							<view class="item-num" v-else>（{{ item.num || (item.friend && item.friend.length) }}）</view>
						</view>

						<view class="item-introduce text-one" v-if="item.friend && item.friend.length">
							<template v-for="it in item.friend">{{ it.realname }}&nbsp;</template>
						</view>
					</view>
					<view v-if="importType != 'age'" class="item-more" @click.stop="show = !show">
						<view class="more-css-icon"></view>
					</view>
				</view>
			</view>
		</checkbox-group>

		<!-- 已选好友列表 -->
		<Popup v-model:show="show" position="bottom" round closeable class="selected-list-popup">
			<view class="title">已选好友（{{ checkUsersList.length }}）</view>
			<checkbox-group class="checkbox-group">
				<view
					v-for="item in checkUsersList"
					:key="item"
					@click.stop="checkedUserChange(item)"
					class="selected-item border-bottom-after"
				>
					<checkbox :value="item.user_id" :checked="item.checked" @click.stop="checkedUserChange(item)" />
					<image class="selected-item__avatar" :src="item.avatar" />
					<view class="selected-item__name"> {{ item.realname }} </view>
				</view>
			</checkbox-group>
		</Popup>
	</view>
</template>

<script>
import NavBar from "@/components/NavBar/NavBar.vue"
import Popup from "@/components/Popup/Popup.vue"
export default {
	data() {
		return {
			title: "",
			rightText: "导入",
			keywords: "",
			show: false,
			list: [],
			ageQuery: {
				min: "",
				max: "",
			},
		}
	},
	components: { NavBar, Popup },
	props: {
		checkUsersList: {
			type: Array,
			default: () => [],
		},
		contacts: {
			type: Array,
			default: () => [],
		},
		importType: {
			type: String,
			default: "",
		},
		friendSelectionShow: {
			type: Boolean,
			default: false,
		},
		checkLabelObj: {
			type: Object,
			default: {
				group: [],
				label: [],
				sex: [],
				age: [],
			},
		},
	},
	watch: {
		list: {
			handler(res) {
				this.checkLabelObj[this.importType].length = 0
				res.forEach((item) => {
					item.checked === 2 && this.checkLabelObj[this.importType].push(item.label_id ?? item.group_id)
				})
			},
			deep: true,
		},
		checkUsersList: {
			handler(res) {
				if (this.importType != "age") {
					this.disposeList(res, this.list)
				}
			},
			deep: true,
		},
	},
	created() {
		this.initTitle()
		this.firstApi()
	},
	methods: {
		initTitle() {
			switch (this.importType) {
				case "group":
					this.title = "选择群聊"
					break
				case "label":
					this.title = "选择标签"
					break
				case "sex":
					this.title = "按性别筛选"
					break
				case "age":
					this.title = "按年龄筛选"
					break
				default:
					this.title = "选择"
			}
		},
		firstApi() {
			if (this.importType === "group") {
				this.getGroups()
			} else if (this.importType === "label") {
				this.getLabels()
			} else if (this.importType === "age") {
				this.getAges()
			} else {
				this.getSexs()
			}
		},
		getAges() {
			const allContacts = uni.getStorageSync("allContacts")
			// console.log(this.contacts, "this contacts")
			const contacts = allContacts.filter((item) => {
				return item.is_group == 0
			})
			const userIds = this.checkUsersList.map((item) => item.user_id)
			contacts.forEach((v) => {
				v.title = v.realname
				if (userIds.includes(v.user_id)) {
					v.checked = 2
				} else {
					v.checked = 0
				}
			})

			const list = contacts.map((v) => {
				return {
					title: v.realname,
					checked: v.checked,
					friend: [v],
				}
			})
			return this.disposeList(this.checkUsersList, list)
		},
		getGroups() {
			this.$api.friendCircleApi.groupfrienduser().then((res) => {
				if (res.code == 0) {
					const resList = res.data ?? []

					this.disposeList(this.checkUsersList, resList)
				}
			})
		},
		getLabels() {
			this.$api.friendCircleApi.imLabel().then((res) => {
				if (res.code == 0) {
					const resList = res.data ?? []

					this.disposeList(this.checkUsersList, resList)
				}
			})
		},
		getSexs() {
			const allContacts = uni.getStorageSync("allContacts")

			const contacts = allContacts.filter((item) => {
				return item.is_group == 0
			})

			const obj = [
				{
					label_id: 0,
					name: "女性朋友",
					friend: [],
				},
				{
					label_id: 1,
					name: "男性朋友",
					friend: [],
				},
				// {
				// 	label_id: 2,
				// 	name: "未知",
				// 	friend: [],
				// },
			]

			contacts.forEach((item) => {
				if (item.sex === 0) {
					obj[0].friend.push(item)
				} else if (item.sex === 1) {
					obj[1].friend.push(item)
				} else {
					// obj[2].friend.push(item);
				}
			})

			this.disposeList(this.checkUsersList, obj)
		},
		getInclude(arr1, arr2) {
			let temp = []
			for (const item of arr2) {
				arr1.find((i) => i === item) ? temp.push(item) : ""
			}
			return temp
		},
		disposeGroupsList(rely, list) {
			console.log(rely, list)
		},
		disposeList(rely, list) {
			// 创建一个包含所有 rely 中 user_id 的数组
			const relyIds = rely.map((item) => item.user_id)
			console.log(relyIds, "relyIds")
			console.log(rely, "rely")
			this.rightText = relyIds.length ? `导入(${relyIds.length})` : "导入"

			list.forEach((item) => {
				if (item.friend.length === 0) {
					item.checked = 0
					return
				}
				console.log(Array.isArray(item.friend), "item")
				const itemUserIds = item.friend.map((friend) => friend.user_id)

				// 判断 itemUserIds 是否都包含在 relyIds 中
				const allMatched = itemUserIds.every((userId) => relyIds.includes(userId))

				if (allMatched) {
					// 如果所有 friend 的 user_id 都在 rely 中
					item.checked = 2
				} else if (itemUserIds.some((userId) => relyIds.includes(userId))) {
					// 如果部分 friend 的 user_id 在 rely 中
					item.checked = 1
				} else {
					// 如果没有任何匹配的 user_id
					item.checked = 0
				}
			})
			this.list = list
			return list
		},
		checkedUserChange(it) {
			const newContacts = [...this.contacts]

			newContacts.forEach((item) => {
				item.children.forEach((child) => {
					child.user_id == it.user_id && (child.checked = !child.checked)
				})
			})

			this.$emit("update:contacts", newContacts)
		},
		checkboxChange(it) {
			console.log(it, "it")
			let newContacts = []
			// 切换 checked 值
			it.checked = it.checked === 2 ? 0 : 2
			// 获取对应的 user_id 列表
			const labelIds = it.friend.map((item) => item.user_id)
			// 深拷贝 contacts
			newContacts = this.contacts.map((item) => ({
				...item,
				children: item.children.map((citem) => ({
					...citem,
					// 如果 user_id 在 labelIds 中，根据 it.checked 设置 checked 值
					checked: labelIds.includes(citem.user_id) ? it.checked === 2 : citem.checked,
				})),
			}))
			console.log(newContacts, "newContacts zheli")
			this.$emit("update:contacts", newContacts)
		},
		handle() {
			console.log(this.contacts, this.list)
		},
		search() {
			console.log("搜索")
		},
		ageSearch() {
			const allList = this.getAges()
			if (this.ageQuery.min === "" && this.ageQuery.max === "") {
				this.getAges()
				return
			}

			const searchList = allList.filter((v) => {
				if (v.friend[0].age >= this.ageQuery.min && v.friend[0].age <= this.ageQuery.max) {
					return v
				}
			})
			this.list = searchList
		},
		onClickLeft() {
			this.$emit("update:importType", "")
			this.$emit("update:friendSelectionShow", true)
		},
		onClickRight() {
			this.$emit("update:importType", "")
			this.$emit("update:friendSelectionShow", true)
		},
	},
}
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
